import 'dart:async';
import 'dart:convert' as convert;
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_constraintlayout/flutter_constraintlayout.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:wch/constant/resource_constant.dart';
import 'package:wch/helper/aio_encode.dart';
import 'package:wch/helper/endian_help.dart';
import 'package:wch/helper/flags_widget.dart';
import 'package:wch/model/ble.dart';
import 'package:wch/model/deviceInfo.dart';
import 'package:wch/model/device_upgrade_model.dart';
import 'package:wch/model/flag_model.dart';
import 'package:wch/utils/color_utils.dart';
import 'package:wch/utils/log_utils.dart';
import 'package:wch/utils/navigator_utils.dart';
import 'package:wch/utils/text_utils.dart';
import 'package:wch/widget/common_widget.dart';
import 'package:wch/widget/padding_widget.dart';
import 'package:wch/widget/text_widget.dart';

import '../constant/event_bus_global.dart';
import '../constant/mqtt_constant.dart';
import '../helper/aio_decode.dart';
import '../helper/event_manager.dart';
import '../helper/mqtt.dart';
import '../helper/preferences_helper.dart';
import '../model/acquisition_entity.dart';
import '../model/device_list_entity.dart';
import '../model/device_version_entity.dart';
import '../model/patient_info_custom.dart';
import '../model/patient_label.dart';
import '../native/native.dart';
import '../native/net_business.dart';
import '../utils/digital_utils.dart';
import '../utils/loading_utils.dart';
import '../utils/toast_utils.dart';
import '../widget/LDashedLine.dart';
import '../widget/alert_view.dart';

class DeliveryDevicePage extends StatefulWidget {
  DeliveryDevicePage({super.key, required this.patientInfoCustom, this.labelList, required this.patientLabelModel});

  final PatientInfoCustom patientInfoCustom;

  final List<AcquisitionAcquisitionLabelList>? labelList;
  ///全部标签
  PatientLabelModel patientLabelModel;

  @override
  State<DeliveryDevicePage> createState() => _DeliveryDevicePageState();
}

class _DeliveryDevicePageState extends State<DeliveryDevicePage> with EventManagerInterface, TickerProviderStateMixin{
  ///设备列表
  List<BleModel> dataList = [];
  ///当前选中的设备
  BleModel? curBleModel;
  ///连接超时 timer
  Timer? connTimer;

  List<Widget> flagWidgets = [];

  double flagHeight = 10;

  double maxWidth = 0;

  OverlayEntry? entry;
  ///一体机信息
  Map<String, dynamic> aioInfo = {};
  ///额贴信息
  Map<String, dynamic> pasterInfo = {};

  List<DeviceListData> deviceList = [];

  // bool pasterUpgrading = false;
  // bool aioUpgrading = false;
  ///订阅主题
  String? topic;
  ///wifi 名称
  String? wifiName;
  StreamSubscription? deviceInfoSubscription;
  StreamSubscription? upgradeSubscription;
  StreamSubscription? queryStateSubscription;
  // StreamSubscription? deliveryDeviceSubscription;
  ///0 未查询 1 查询一体机状态 2 查询脑贴状态
  int queryState = 0;
  ///升级状态,-1 未开始，0 正在下载，1 开始升级，2 升级完成
  int aioUpgradeStatus = -1;
  int pasterUpgradeStatus = -1;
  ///是否有新的一体机版本
  bool hasNewAioVer = true;
  bool hasNewPasterVer = true;
  bool delDeviceInfo = false;
  ///获取 wifi 名称定时器
  Timer? wifiNameTimer;
  ///搜索超时
  Timer? searchTimer;
  ///是否搜索中
  bool isSearching = true;
  ///是否展示采集标签
  bool isShowFlag = false;

  AnimationController? animationController;
  Animation<double>? animation;

  @override
  Widget build(BuildContext context) {

    return CommonScaffold(title: '分配设备', body: Container(
      margin: EdgeInsets.all(15.w),
      color: Color(0xFFF8F9FB),
      child: ConstraintLayout(
        children: [
          SingleChildScrollView(
            child: Column(
              children: [
                Container(
                  height: 70.h + flagHeight + (widget.patientInfoCustom.name.length > 3 ? 20.h : 0),
                  width: ScreenUtil().screenWidth - 30.w,
                  decoration: BoxDecoration(
                      color: themeColor,
                      borderRadius: BorderRadius.all(Radius.circular(7.5.w))
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      VerPadding(20.h),
                      widget.patientInfoCustom.name.length > 3 ? Column(
                        children: [
                          Row(
                            children: [
                              HorPadding(17.5.w),
                              Image.asset(widget.patientInfoCustom.sex == '男' ? patientMaleImg : patientFemaleImg, width: 35.w, height: 35.w,),
                              HorPadding(5.w),
                              Container(
                                  constraints: BoxConstraints(maxWidth: ScreenUtil()
                                      .screenWidth - 130.w),
                                  child: MyText(
                                      widget.patientInfoCustom.name ?? '', overflow: TextOverflow
                                      .ellipsis, color: Colors.white, fontSize: 20)),
                              HorPadding(5.w),
                              Container(
                                width: 20.w,
                                height: 20.w,
                                decoration: BoxDecoration(
                                  image: DecorationImage(image: AssetImage(widget.patientInfoCustom.sex == '男' ? patientMale2Icon :patientFemale2Icon),
                                      fit: BoxFit.none, scale:2),
                                  color: Color(0xFFDEE5FB),
                                  borderRadius: BorderRadius.all(
                                      Radius.circular(10.w)),
                                ),
                              ),

                            ],
                          ),
                          VerPadding(6.h),
                          Row(
                            children: [
                              HorPadding(25.w),
                              F14TitleText('${widget.patientInfoCustom.age ?? 0}岁', color: Colors.white),
                              HorPadding(4.w),
                              Expanded(child: F14TitleText(widget.patientInfoCustom.mobile ?? '', color: Colors
                                  .white)),
                              HorPadding(17.5.w),
                            ],
                          )
                        ],
                      ) : Row(
                        children: [
                          HorPadding(17.5.w),
                          Image.asset(widget.patientInfoCustom.sex == '男' ? patientMaleImg : patientFemaleImg, width: 35.w, height: 35.w,),
                          HorPadding(5.w),
                          Container(
                              constraints: BoxConstraints(maxWidth: ScreenUtil()
                                  .screenWidth - 280.w),
                              child: MyText(
                                  widget.patientInfoCustom.name ?? '', overflow: TextOverflow
                                  .ellipsis, color: Colors.white, fontSize: 20)),
                          HorPadding(5.w),
                          Container(
                            width: 20.w,
                            height: 20.w,
                            decoration: BoxDecoration(
                                image: DecorationImage(image: AssetImage(widget.patientInfoCustom.sex == '男' ? patientMale2Icon :patientFemale2Icon),
                                  fit: BoxFit.none, scale:2),
                              color: Color(0xFFDEE5FB),
                              borderRadius: BorderRadius.all(
                                  Radius.circular(10.w)),
                            ),
                          ),
                          HorPadding(25.w),
                          F14TitleText('${widget.patientInfoCustom.age ?? 0}岁', color: Colors.white),
                          HorPadding(4.w),
                          Expanded(child: F14TitleText(widget.patientInfoCustom.mobile ?? '', color: Colors
                              .white)),
                          HorPadding(17.5.w),
                        ],
                      ),
                      Visibility(
                        visible: flagHeight > 0,
                        child: Row(
                          children: [
                            Container(
                              margin: EdgeInsets.symmetric(horizontal: 20.w),
                              width: maxWidth,
                              height: flagHeight,
                              child: Stack(
                                children: flagWidgets,
                              ),
                            ),
                            GestureDetector(
                              onTap: () {
                                entry = OverlayEntry(builder: (ctx) {
                                  List<PatientAllLabelData>? labelData = widget
                                      .patientLabelModel.data;
                                  if (labelData != null && labelData.isNotEmpty) {
                                    for (int i = 0; i < labelData!.length; i ++) {
                                      labelData[i].isChecked = false;
                                    }
                                    List<
                                        AcquisitionAcquisitionLabelList>? patientShopLabelList = widget
                                        .labelList;
                                    if (patientShopLabelList != null &&
                                        patientShopLabelList.isNotEmpty) {
                                      for (int i = 0; i <
                                          labelData!.length; i ++) {
                                        for (int j = 0; j <
                                            patientShopLabelList!.length; j ++) {
                                          AcquisitionAcquisitionLabelList label = patientShopLabelList[j];
                                          if (labelData[i].name == label.name) {
                                            labelData[i].isChecked = true;
                                          }
                                        }
                                      }
                                    }
                                  }
                                  return EditFlagAlert(title: '添加采集标签', entry: entry!, flagModels: widget.patientLabelModel.data!, actionCallback: (List<PatientAllLabelData> labelList){
                                    if (labelList.isEmpty){
                                      return;
                                    }
                                    List<Map<String, dynamic>> idList = [];
                                    List<Map<String, String>> list = [];
                                    for(int i = 0; i < labelList.length; i ++) {
                                      PatientAllLabelData data = labelList[i];
                                      if (data.isChecked) {
                                        Map<String, String> m = <String, String>{};
                                        m['id'] = data.id!;
                                        m['name'] = data.name!;
                                        m['colour'] = data.colour!;
                                        list.add(m);
                                        idList.add({'id': data.id!});
                                      }
                                    }

                                    NetBusiness().patientAcquisitionAddLabel(widget.patientInfoCustom.userId!, idList).then((value) {
                                      if (value) {
                                        ///重新查询患者详情，以拿到更新后的患者标签
                                        widget.labelList!.clear();
                                        for (int i = 0; i < list.length; i ++) {
                                          Map<String, String> m = list[i];
                                          AcquisitionAcquisitionLabelList label = AcquisitionAcquisitionLabelList();
                                          label.colour = m['colour'];
                                          label.id = m['id'];
                                          label.name = m['name'];
                                          widget.labelList!.add(label);
                                        }
                                        setState(() {
                                          _getFlagWidget();
                                        });
                                        globalEventBus.fire(EventBufRefreshModel());
                                      }
                                    });
                                  });
                                }
                                );
                                Overlay.of(context).insert(entry!);
                              }, child: Container(
                              width: 84.w,
                              height: 31.h,
                              // padding: EdgeInsets.symmetric(horizontal: 6.w),
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.all(
                                      Radius.circular(15.5.h)),
                                  border: Border.all(color: Colors.white, width: 0.5)
                              ),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                children: [
                                  Image.asset(
                                    addFlagIcon, width: 17.w, height: 17.w,),
                                  F12TitleText('添加标签', color: Colors.white)
                                ],
                              ),
                            ),
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                VerPadding(10.h),
                Container(
                  width: ScreenUtil().screenWidth - 30.w,
                  height: 52.h * 5,
                  // padding: EdgeInsets.symmetric(horizontal: 15.w),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(7.5.w)),
                  ),
                  child: Column(
                    children: [
                      Row(
                        children: [
                          HorPadding(15.w),
                          Container(
                            child: Text('搜索到以下终端', style: TextStyle(
                                color: Color(0xFF262626),
                                fontSize: 17
                            ),),
                            height: 52.h,
                            alignment: Alignment.centerLeft,
                          ),
                          GestureDetector(
                            onTap: (){
                              NativeUtils.bleCentralState();
                              NativeUtils.stopScanAIO();
                              setState(() {
                                dataList.clear();
                              });
                              getDeviceList();
                              isSearching = true;
                              searchTimer?.cancel();
                              searchTimer = Timer(Duration(seconds: 10), (){
                                setState(() {
                                  isSearching = false;
                                });
                              });
                              NativeUtils.scanAIO();
                            },
                            child: Container(
                              padding: EdgeInsets.all(10.w),
                              child: Image.asset(
                                refreshDeviceIcon, width: 16.w, height: 16.w,),
                            ),
                          )
                        ],
                      ),
                      LineWidget(
                          width: ScreenUtil().screenWidth - 60.w, height: 0.5),
                      Expanded(
                        child: isSearching ? buildRotationTransition() : dataList.isEmpty ? Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Image.asset(aioEmptyIcon, width: 71.w, height: 52.h,),
                            VerPadding(4.h),
                            F12TitleText('未搜索到任何设备', color: Color(0xFF868686)),
                          ],
                        ) : RawScrollbar(
                          thumbVisibility:dataList.length >= 4 ? true : false,
                          thumbColor: themeColor.withOpacity(0.1),
                          radius: Radius.circular(10),
                          child: ListView.separated(itemBuilder: (ctx, id) {
                            return _getItem(id);
                          }, separatorBuilder: (ctx, id) {
                            return Container(
                              padding: EdgeInsets.symmetric(horizontal: 12.5.w),
                              child: const Divider(
                                  height: 0.5, thickness: 0.5, color: lineColor),
                            );
                          }, itemCount: dataList.length),
                        ),
                      ),
                    ],
                  ),
                ),
                VerPadding(10.h),
                Container(
                  height: _getAioUIStatus() ? 380.h : 130.h,
                  width: ScreenUtil().screenWidth - 30.w,
                  padding: EdgeInsets.symmetric(horizontal: 15.w),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(7.5.w))
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          VerPadding(20.h),
                          Text('已配对终端', style: TextStyle(
                              color: Color(0xFF262626),
                              fontSize: 17
                          )),
                          VerPadding(5.h),
                          Row(
                            children: [
                              _getDescLabel(
                                  '设备名称：${aioInfo['name'] ?? ''}'),
                              HorPadding(10.w),
                              Visibility(
                                visible: _getAioUIStatus(),
                                child: Container(width: 75.w,
                                  height: 31.h,
                                  child: _getWifiStatus() ? GestureDetector(onTap: (){
                                    if (wifiName == 'empty') {
                                      entry = OverlayEntry(builder: (ctx){
                                        return CommonAlert(title: '配网提示', msg: '终端需要连接网络使用，请将手机连接Wi-Fi后进行一体机配网', callback: (id){}, entry: entry!, isSingleBtn:true, leftBtnText: '确定',);
                                      });
                                      Overlay.of(context).insert(entry!);
                                      return;
                                    }
                                    entry = OverlayEntry(builder: (ctx){
                                      return AlertInputWidget(callback: (id, pass){
                                        if (id == 0) {
                                          ToastUtils.showToast(msg: '配网失败');
                                          return;
                                        }
                                        _setWifi(pass);
                                      }, title: '配网设置', entry: entry!, btns: ['取消', '确定'], msg: 'Wi-Fi名称：$wifiName', hint: '请输入密码',);
                                    });
                                    Overlay.of(context).insert(entry!);
                                  }, child: F12TitleText('已连接Wi-Fi', color: Color(0xFF118291))) : CommonBtn(title: '连接Wi-Fi', fontSize: 12, callback: (){
                                    if (wifiName == 'empty') {
                                      entry = OverlayEntry(builder: (ctx){
                                        return CommonAlert(title: '配网提示', msg: '终端需要连接网络使用，请将手机连接Wi-Fi后进行一体机配网', callback: (id){}, entry: entry!, isSingleBtn:true, leftBtnText: '确定',);
                                      });
                                      Overlay.of(context).insert(entry!);
                                      return;
                                    }
                                    entry = OverlayEntry(builder: (ctx){
                                      return AlertInputWidget(callback: (id, pass){
                                        if (id == 0) {
                                          ToastUtils.showToast(msg: '配网失败');
                                          return;
                                        }
                                        _setWifi(pass);
                                      }, title: '配网设置', entry: entry!, btns: ['取消', '确定'], msg: 'Wi-Fi名称：$wifiName', hint: '请输入密码',);
                                    });
                                    Overlay.of(context).insert(entry!);
                                  },)),
                              )
                            ],
                          ),
                          _getDescLabel('版本：${aioInfo['version'] ?? ''}'),
                          !_getAioUIStatus() ? Container() : GestureDetector(
                            onTap: () async{
                              if (!hasNewAioVer) {
                                ToastUtils.showToast(msg: '当前固件已是最新版本');
                                return;
                              }
                              if (aioUpgradeStatus == 0) {
                                ToastUtils.showToast(msg: '正在下载固件版本中');
                                return;
                              } else if (aioUpgradeStatus == 1) {
                                ToastUtils.showToast(msg: '正在升级固件版本中');
                                return;
                              }
                              if (pasterUpgradeStatus == 0 || pasterUpgradeStatus == 1) {
                                ToastUtils.showToast(msg: '脑贴正在升级固件中');
                                return;
                              }
                              if (aioInfo['wifi_open'] == false || aioInfo['wifi_connected'] == false) {
                                ToastUtils.showToast(msg: '请配置网络后再固件升级');
                                return;
                              }

                              int compare = await checkVersionType('ANDROID_AIO', aioInfo['version']);
                              if (compare == 1) {
                                ToastUtils.showToast(msg: '当前终端已是最新版本');
                                return;
                              }
                              // queryState = 1;
                              // String pubTopic = 'RL/SAAS/${curBleModel!.deviceName}/APP';
                              // Map<String, dynamic> msg = {'messageType': mqttDeviceInfo};
                              // mqttPublicMsg(pubTopic, convert.jsonEncode(msg));
                            },
                            child: Center(
                                child: Text('固件升级', style: TextStyle(
                                    color: themeColor,
                                    fontSize: 12,
                                    fontWeight: FontWeight.w500
                                ),)
                            ),
                          ),
                          VerPadding(15.h),
                        ],
                      ),
                      _getAioUIStatus() == false ? Container() :Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          LDashedLine(axis: Axis.horizontal,
                            dashedWidth: 8.w,
                            count: (ScreenUtil().screenWidth - 60.w) ~/ 12.w,
                            dashedHeight: 1,
                            dashedColor: Color(0xFFE6E6E6),
                            dashedTotalLengthWith: ScreenUtil().screenWidth - 60.w,),
                          VerPadding(15.h),
                          Text('脑贴信息', style: TextStyle(
                              color: Color(0xFF262626),
                              fontSize: 17
                          )),
                          VerPadding(8.h),
                          _getDescLabel2('设备名称：${pasterInfo['name'] ?? ''}'),
                          _getDescLabel2('设备电量：${pasterInfo['battery'] == null ? '-' : '${pasterInfo['battery']}%'}'),
                          _getDescLabel2('连接状态：${_getPasterStatus()}'),
                          _getDescLabel2('信号：${pasterInfo['signal'] ?? ''}'),
                          _getDescLabel2('版本号：${pasterInfo['version'] ?? '-'}'),
                          VerPadding(5.h),
                          GestureDetector(
                            onTap: () async{
                              if (!hasNewPasterVer) {
                                ToastUtils.showToast(msg: '当前固件已是最新版本');
                                return;
                              }
                              if (pasterUpgradeStatus == 0) {
                                ToastUtils.showToast(msg: '正在下载固件版本中');
                                return;
                              } else if (pasterUpgradeStatus == 1) {
                                ToastUtils.showToast(msg: '正在升级固件版本中');
                                return;
                              }
                              if (aioUpgradeStatus == 0 || aioUpgradeStatus == 1) {
                                ToastUtils.showToast(msg: '终端正在升级固件中');
                                return;
                              }
                              if (aioInfo['wifi_open'] == false || aioInfo['wifi_connected'] == false) {
                                ToastUtils.showToast(msg: '请配置网络后再固件升级');
                                return;
                              }

                              LogUtils.log('---=${pasterInfo['name']}');
                              LogUtils.log('---=${pasterInfo['version']}');
                              String deviceName = pasterInfo['name'] ?? '';
                              int start = deviceName.indexOf('-');
                              int end = deviceName.lastIndexOf('-');
                              String deviceType = deviceName.substring(start+1, end);
                              int compare = await checkVersionType(deviceType, pasterInfo['version']);
                              LogUtils.log('compare=$compare');
                              if (compare == 1) {
                                Loading.getIns().hide();
                                ToastUtils.showToast(msg: '当前脑贴已是最新版本');
                                return;
                              }

                              queryState = 2;
                              String pubTopic = 'RL/SAAS/${curBleModel!.deviceName}/APP';
                              Map<String, dynamic> msg = {'messageType': mqttDeviceInfo};
                              mqttPublicMsg(pubTopic, convert.jsonEncode(msg));

                            },
                            child: Center(
                                child: Text('固件升级', style: TextStyle(
                                    color: themeColor,
                                    fontSize: 12,
                                    fontWeight: FontWeight.w500
                                ),)
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ).applyConstraint(
            left: parent.left,
            top: parent.top,
            right: parent.right,
            bottom: parent.bottom.margin(70.h),
            height: matchConstraint
          ),
          Column(
            children: [
              VerPadding(15.h),
              Visibility(
                visible: curBleModel != null && curBleModel?.isConnected != false,
                child: Container(
                  width: ScreenUtil().screenWidth - 80.w,
                  child: CommonBtn(
                    title: '确认分配',
                    isEnable: _getBtnStatus(),
                    callback: (){
                      deliveryDevice();
                    },
                  ),
                ),
              ),
              // VerPadding(15.h),
            ],
          ).applyConstraint(
              left: parent.left,
              right: parent.right,
              width: matchConstraint,
              bottom: parent.bottom.margin(10.h),
              height: 60.h
          )
        ],
      ),
    ));
  }

  void deliveryDevice() {

    // if (upgradingAio != null) {
    //   ToastUtils.showToast(msg: '一体机正在升级，请等待');
    //   return;
    // }
    // if (upgradingPaster != null) {
    //   ToastUtils.showToast(msg: '脑贴正在升级，请等待');
    //   return;
    // }
    // String pubTopic = 'RL/SAAS/${curBleModel!.deviceName}/APP';
    // Map<String, dynamic> msg = {'messageType': mqttDeviceInfo};
    // mqttPublicMsg(pubTopic, convert.jsonEncode(msg));
    // Loading.getIns().loading(msg: '正在分配中');
    // deliveryTimer = Timer(Duration(seconds: 30), (){
    //   Loading.getIns().hide();
    //   ToastUtils.showToast(msg: '查询终端信息超时');
    //   deliveryDeviceSubscription?.cancel();
    // });

    // deliveryDeviceSubscription = globalEventBus.on<DeviceInfoModel>().listen((onData){
      Loading.getIns().hide();
      // deliveryDeviceSubscription!.cancel();
      // deliveryTimer!.cancel();
      // if (onData.workStatus == 'Y') {
      //   ToastUtils.showToast(msg: '设备当前正在使用中，不能分配');
      //   ///取消timer
      //   deliveryTimer!.cancel();
      //   return;
      // }

      NetBusiness().deliveryDevice(curBleModel!.deviceId, widget.patientInfoCustom.userId, curBleModel!.deviceName).then((value){
        if (value) {
          ToastUtils.showToast(msg: '分配设备成功');
          // if (widget.callback != null) {
          //   widget.callback(1);
          // }
          NavigatorUtil.pop(context);
          String publicTopic = 'RL/SAAS/${curBleModel!.deviceName}/APP';
          Map<String, dynamic> msg = {};
          msg['messageType'] = 'bindSickPerson';
          msg['data'] = {
            'token':PreferencesHelper.getUserToken(),
            'sickPersonId':widget.patientInfoCustom.userId
          };
          mqttPublicMsg(publicTopic, convert.jsonEncode(msg));

          globalEventBus.fire(EventBufRefreshModel());
        } else {
          ToastUtils.showToast(msg: '分配设备失败，请稍后再试');
        }
      });
    // });
  }

  void _setWifi(String pass) {
    LogUtils.log('配网==');
    List<int> wifiList = EndianUtils.getBytesFixLen(wifiName!, EndianUtils.utf8Coding, 64);
    List<int> passList = EndianUtils.getBytesFixLen(pass, EndianUtils.utf8Coding, 20);
    List<int> cmdList = AIOEncode.setWifiInfo(wifi: wifiList, pass: passList);
    Loading.getIns().loading(msg: '正在配网中');
    NativeUtils.nativeAIOListener(cmdList);
    Timer.periodic(const Duration(seconds: 20), (timer) {
      timer.cancel();
      Loading.getIns().hide();
    });
  }
  bool _getBtnStatus() {
    if (aioUpgradeStatus != -1 && aioUpgradeStatus != 2) {
      return false;
    }
    if (pasterUpgradeStatus != -1 && pasterUpgradeStatus != 2) {
      return false;
    }
    bool? wifiOpen = aioInfo['wifi_open'];
    bool? wifiConnected = aioInfo['wifi_connected'];
    if (wifiOpen == null || wifiConnected == null) {
      return false;
    }
    return wifiOpen && wifiConnected;
  }
  ///一体机信息是否展示
  bool _getAioUIStatus() {
    bool? status = aioInfo['aio_status'];
    if (status != null) {
      return status ? true : false;
    }
    return false;
  }
  bool _getWifiStatus() {
    if (aioInfo['status'] != null) {
      return aioInfo['status'] == 'Y';
    }
    bool? wifiOpen = aioInfo['wifi_open'];
    bool? wifiConnected = aioInfo['wifi_connected'];
    if (wifiOpen == null || wifiConnected == null) {
      return false;
    }

    return wifiOpen && wifiConnected;
  }
  String _getPasterStatus() {
    bool? status = pasterInfo['status'];
    if (status != null) {
      return status ? '已连接' : '未连接';
    }
    return '未连接';
  }

  Widget _getDescLabel(String desc) {
    return Container(
      alignment: Alignment.center,
      height: 32.h,
      width: ScreenUtil().screenWidth - 146.w,
      child: Row(
        children: [
          Container(width: ScreenUtil().screenWidth - 146.w,
              child: F15TitleText(
                desc, color: F2TextColor, overflow: TextOverflow.ellipsis,)),
        ],
      ),
    );
  }
  Widget _getDescLabel2(String desc) {
    return Container(
      alignment: Alignment.center,
      height: 32.h,
      width: ScreenUtil().screenWidth - 60.w,
      child: Row(
        children: [
          Container(width: ScreenUtil().screenWidth - 60.w,
              child: F15TitleText(
                desc, color: F2TextColor, overflow: TextOverflow.ellipsis,)),
        ],
      ),
    );
  }

  Widget _getItem(int index) {
    BleModel model = dataList[index];
    return Container(
      height: 52.h,
      width: ScreenUtil().screenWidth - 60.w,
      padding: EdgeInsets.symmetric(horizontal: 12.5.w),
      child: Row(
        children: [
          Container(width: ScreenUtil().screenWidth - 135.w,
              child: F15TitleText('${model.deviceName}', color: F2TextColor,
                overflow: TextOverflow.ellipsis,)),
          HorPadding(10.w),
          Container(width: 65, height: 31, child: !model.isConnected ? CommonBtn(title: '配对', fontSize: 12, callback: (){
            if (curBleModel == null || !curBleModel!.isConnected) {
              Map map = {'deviceName': model.deviceName, 'mac': model.mac};
              LogUtils.log('map=$map');
              NativeUtils.connectAIO(arguments: {'deviceName': model.deviceName, 'mac': model.mac});
              Loading.getIns().loading(msg: '正在连接终端...');
              curBleModel = model;
              ///TODO:  需优化
              ///30秒后关闭弹窗
              connTimer = Timer.periodic(const Duration(seconds: 30), (timer) {
                timer.cancel();
                Loading.getIns().hide();
                ToastUtils.showToast(msg: '连接超时');
              });
            } else {
              ToastUtils.showToast(msg: '已成功配对终端，不可重复配对');
            }

          },) : GestureDetector(
            onTap: (){
              NativeUtils.disconnectAIO();
              setState(() {
                model.isConnected = false;
                curBleModel = null;
                aioInfo.clear();
                pasterInfo.clear();
                mqttCancelSubscribe(topic!);
                queryState = 0;
                connTimer?.cancel();
                searchTimer?.cancel();
                aioUpgradeStatus = -1;
                pasterUpgradeStatus = -1;
                deviceInfoSubscription?.cancel();
                upgradeSubscription?.cancel();
                queryStateSubscription?.cancel();
              });
            },
            child: Container(
              width: 65,
              height: 31,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(15.5)),
                border: Border.all(color: themeColor, width: 0.5)
              ),
              child: const Text('取消', style: TextStyle(fontSize: 12, color: themeColor, fontWeight: FontWeight.w600),)
            ),
          ))
        ],
      ),
    );
  }

  ///重新查询患者详情
  void refreshPatientDetail() {
    NetBusiness().patientDetail(widget.patientInfoCustom.userId!).then((value) {

    });
  }

  @override
  void initState() {

    /// 动画持续时间是 3秒，此处的this指 TickerProviderStateMixin
    animationController = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )
      ..repeat();
    animation = Tween<double>(begin: 1, end: 0).animate(animationController!);

    EventManager.getIns().addObserver(this);
    NativeUtils.bleCentralState();
    wifiNameTimer = Timer.periodic(Duration(seconds: 1), (timer){
      NativeUtils.getWifiName();
    });

    searchTimer = Timer.periodic(Duration(seconds: 10), (timer){
      setState(() {
        isSearching = false;
      });
    });

    if (Platform.isIOS) {
      NativeUtils.startIOSLocation();
    }

    _getFlagWidget();

    getDeviceList();

    ///数据更新
    queryStateSubscription = globalEventBus.on<DeviceInfoModel>().listen((onData){
      LogUtils.log('queryState=$queryState');
      if (queryState == 0) {
        return;
      }
      if (queryState == 1) {
        // if (aioUpgrading)  return;
        // setState(() {
        //   aioUpgrading = true;
        // });
        //发布消息
        String publicTopic = 'RL/SAAS/${aioInfo['name']}/APP';
        Map<String, dynamic> msg = {'messageType':'aio_upgrade'};
        mqttPublicMsg(publicTopic, convert.jsonEncode(msg));

        // upgradingAio = aioInfo['name'];
      } else {
        // if (pasterUpgrading)  return;
        // setState(() {
        //   pasterUpgrading = true;
        // });
        //发布消息
        String publicTopic = 'RL/SAAS/${aioInfo['name']}/APP';
        LogUtils.log('publicTopic=$publicTopic');
        Map<String, dynamic> msg = {'messageType':'eeg_upgrade'};
        mqttPublicMsg(publicTopic, convert.jsonEncode(msg));

        // upgradingPaster = pasterInfo['name'];
      }
      queryState = 0;

    });
    upgradeSubscription = globalEventBus.on<DeviceUpgradeModel>().listen((onData){
      // LogUtils.log('upgradeSubscription=${onData.type}');
      if (onData.type == 1) {
        LogUtils.log('onData=$onData');
        if (onData.status == 0) {
          ToastUtils.showToast(msg: '正在下载终端固件', len: Toast.LENGTH_SHORT);
          aioUpgradeStatus = 0;
        } else if (onData.status == 1) {
          ToastUtils.showToast(msg: '正在升级终端固件', len: Toast.LENGTH_SHORT);
          aioUpgradeStatus = 1;
        } else if (onData.status == 2) {
          ToastUtils.showToast(msg: '升级终端固件完成', len: Toast.LENGTH_SHORT);
          aioUpgradeStatus = 2;
          ///重新连接一体机
          Timer.periodic(Duration(seconds: 1), (timer){
            timer.cancel();
            NativeUtils.connectAIO(arguments: {'deviceName': curBleModel!.deviceName, 'mac': curBleModel!.mac});
            Loading.getIns().loading(msg: '正在连接终端...');
          });
        } else if (onData.status == 3) {
          ToastUtils.showToast(msg: '升级终端固件失败', len: Toast.LENGTH_SHORT);
          aioUpgradeStatus = -1;
        }
        setState(() {
          aioUpgradeStatus;
        });
      } else if (onData.type == 2) {
        LogUtils.log('upgradeSubscription=${onData.status}');
        if (onData.status == 0) {
          ToastUtils.showToast(msg: '正在下载脑贴固件', len: Toast.LENGTH_SHORT);
          pasterUpgradeStatus = 0;
        } else if (onData.status == 1) {
          ToastUtils.showToast(msg: '正在升级脑贴固件', len: Toast.LENGTH_SHORT);
          pasterUpgradeStatus = 1;
        } else if (onData.status == 2) {
          ToastUtils.showToast(msg: '升级脑贴固件完成', len: Toast.LENGTH_SHORT);
          pasterUpgradeStatus = 2;
        } else if (onData.status == 3) {
          ToastUtils.showToast(msg: '升级脑贴固件失败', len: Toast.LENGTH_SHORT);
          pasterUpgradeStatus = -1;
        }
        setState(() {
          pasterUpgradeStatus;
        });
      }
    });
    deviceInfoSubscription = globalEventBus.on<DeviceInfoModel>().listen((onData){
      LogUtils.log('deviceInfoSubscription');
      setState(() {
        aioInfo['name'] = onData.aioName;
        aioInfo['version'] = onData.aioVersion;
        aioInfo['upgrade'] = onData.aioUpgradeStatus;
        aioInfo['workStatus'] = onData.aioWorkStatus;
        aioInfo['status'] = onData.aioWifiStatus;

        pasterInfo['name'] = onData.deviceName;
        pasterInfo['version'] = onData.deviceVersion;
        onData.battery ??= '0';
        pasterInfo['battery'] = onData.battery;
        pasterInfo['workStatus'] = onData.workStatus;
        pasterInfo['signal'] = onData.signal;
        pasterInfo['status'] = onData.connStatus == 'Y';

      });
    });

    ///获取医院配置信息
    NetBusiness().hospitalConfig().then((onValue){
      setState(() {
        if (onValue.data?.isLabelConfig == 'N') {
          flagHeight = 0;
        }
      });
    });

    NetBusiness().patientAllLabel(0).then((value){
      widget.patientLabelModel = value;
    });
  }

  Future<int> checkVersionType(String deviceType, String version) async {
    LogUtils.log('log=$deviceType');
    LogUtils.log('log=$version');
    Loading.getIns().loading(msg: '正在检测版本');
    DeviceVersionEntity entity = await NetBusiness().deviceVersion(deviceType, version);
    Loading.getIns().hide();
    String serverDeviceType = entity.data!.versionNum!;
    if (serverDeviceType.contains('V')){
      serverDeviceType = serverDeviceType.substring(1);
    }
    if (version.contains('V')){
      version = version.substring(1);
    }
    return DigitalUtils.compareVersionType(serverDeviceType, version);
  }

  void getDeviceList() {
    NetBusiness().deviceList().then((value){
      deviceList = value.data!;
      NativeUtils.scanAIO();
    });
  }

  void _getFlagWidget() {
    Text label = Text('采集标签：', style: TextStyle(
        fontSize: 12, color: Colors.white
    ),);

    maxWidth = ScreenUtil().screenWidth - 170.w;
    double labelWidth = TextUtils
        .getTextSize('采集标签：', maxWidth, 12)
        .width + 10;
    List<FlagModel> flags = [];
    if (widget.labelList != null) {
      for(int i = 0; i < widget.labelList!.length; i ++) {
        Color textColor = ColorUtils.getColorFromHex(widget.labelList![i].colour!);
        Color backgroundColor = Colors.white;
        flags.add(FlagModel(widget.labelList![i].name!, false, backgroundColor, textColor));
      }
    }

    flagWidgets = FlagsWidget.getFlagsWidgetAndHead2(
        label,
        labelWidth,
        flags,
        maxWidth,
        180,
        10, (_flagHeight) {
      flagHeight = _flagHeight;
    });
  }

  @override
  void dispose() {
    animationController?.dispose();
    super.dispose();
    ///释放
    NativeUtils.stopScanAIO();
    NativeUtils.disconnectAIO();
    EventManager.getIns().removeObserver(this);
    connTimer?.cancel();
    wifiNameTimer?.cancel();
    searchTimer?.cancel();
    // deliveryTimer?.cancel();
    if (topic != null) {
      mqttCancelSubscribe(topic!);
    }

    deviceInfoSubscription?.cancel();
    upgradeSubscription?.cancel();
    queryStateSubscription?.cancel();
    // deliveryDeviceSubscription?.cancel();
  }
  //旋转
  Widget buildRotationTransition() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          RotationTransition(
            //设置动画的旋转中心
            alignment: Alignment.center,
            //动画控制器
            turns: animation!,
            //将要执行动画的子view
            child: Image.asset(searchLoadingIcon, width: 40.w, height: 40.w,),
          ),
          VerPadding(14.h),
          F14TitleText('搜索中...', color: Color(0xFF515151)),
        ],
      ),
    );
  }

  ///判断搜索到的设备是否需要显示
  void deviceShowLogic(Map<dynamic, dynamic> searchData) {
    bool isShow = true;///未被分配
    String? deviceId;
    String deviceName = searchData['deviceName'];
    LogUtils.log('deviceName=$deviceName');
    for(int i = 0; i < deviceList.length; i ++) {
      if (deviceList[i].deviceBluetoothNumber == deviceName) {
        if (deviceList[i].sickPersonId != null) {
          isShow = false;
        }
        deviceId = deviceList[i].id!;
        break;
      }
    }
    if (isShow) {
      String channel = searchData['channelName'];
      int code = searchData['code'];
      // String deviceName = searchData['deviceName'];
      bool isConnected = searchData['isConnected'];
      String? mac = searchData['mac'];
      ///判断设备是否已被分配
      BleModel model = BleModel(channelName: channel, code: code, deviceName: deviceName, isConnected: isConnected, mac: mac, deviceId: deviceId);
      setState(() {
        dataList.add(model);
        isSearching = false;
      });
    }
  }

  @override
  void notify(String methodName, Map<dynamic, dynamic> data) {
    // TODO: implement notify
    if (methodName == eventScanAIO) {
      deviceShowLogic(data);
    } else if (methodName == eventBleCentralState) {
      int isOpen = data['BLECentralStatus'];
      if (isOpen == 0) {
        // ToastUtils.showToast(msg: '请检查手机蓝牙开启状态');
        entry = OverlayEntry(builder: (ctx){
          return CommonAlert(title: '温馨提示', msg: '请检查手机蓝牙是否打开', callback: (id){}, leftBtnText: '确定', isSingleBtn: true, entry: entry!);
        });
        Overlay.of(context).insert(entry!);
        NativeUtils.stopScanAIO();
      } else if (isOpen == -1) {
        entry = OverlayEntry(builder: (ctx){
          return CommonAlert(title: '温馨提示', msg: '请检查蓝牙权限是否打开', callback: (id){}, leftBtnText: '确定', isSingleBtn: true, entry: entry!);
        });
        Overlay.of(context).insert(entry!);
        NativeUtils.stopScanAIO();
      }
    } else if (methodName == eventConnectStatus) {

      String deviceName = data['deviceName'];
      bool isConnected = data['isConnected'];

      if (!isConnected) {
        // ToastUtils.showToast(msg: '设备已断连');
        setState(() {
          aioInfo.clear();
          pasterInfo.clear();
        });
      } else {
        Loading.getIns().hide();
        connTimer!.cancel();
        topic = 'RL/SAAS/$deviceName';
        mqttSubscribe(topic!);

        // deviceInfoEntity.resetInfo();
        // deviceInfoEntity.connected = true;
        // deviceInfoEntity.deviceNumber = deviceName;

        // List<int> tokenList = EndianUtils.getBytes(PreferencesHelper.getUserToken()!, EndianUtils.gbkCoding);
        // List<int> timeList = EndianUtils.toBytesFromNumStr(TimeUtils.getCurTime());
        // // String memberId = '${PreferencesHelper.getMemberId()!}';
        // String memberId = '1960001';
        // List<int> userList = EndianUtils.getBytes(memberId, EndianUtils.gbkCoding);
        // List<int> timeAreaList = [8, 12];
        // int len = tokenList.length+userList.length+timeList.length+timeAreaList.length;
        //
        // List<int> cmdList = [-69, 1, 0, 0];
        // cmdList.add(len);
        // cmdList.addAll(tokenList);
        // cmdList.addAll(timeList);
        // cmdList.addAll(timeAreaList);
        // cmdList.addAll(userList);
        // Loading.getIns().loading(msg: '正在配对中');
        // NativeUtils.nativeAIOListener(cmdList);
      }

      for(int i = 0; i < dataList.length; i ++) {
        BleModel entity = dataList[i];
        if (entity.deviceName == deviceName) {
          entity.isConnected = isConnected;
          break;
        }
      }

      setState(() {
        dataList;
      });

      if (isConnected) {//查询一体机信息
        List<int> cmdList = [0xbb, 0x0b, 0x00, 0x00, 0x00];
        LogUtils.log('查询一体机信息');
        NativeUtils.nativeAIOListener(cmdList);
      }

    } else if (methodName == getEventWifi) {
      wifiName = data['wifiName'];
    } else if (methodName == eventBluetooth) {
      String deviceName = data['deviceName'];
      List<int> cmdList = data['cmd'];
      DecodeEntity decodeEntity = AIODecode.decodeData(cmdList);
      debugPrint('decodeEntity.name=${decodeEntity.name}');
      if (decodeEntity.name == 'auth') {
        // ToastUtils.showToast(msg: '配对成功');
        Loading.getIns().hide();
        if(decodeEntity.validateResult==1){//绑定成功
          connTimer?.cancel();

          // DeviceConfigEntity.getInstance().isBind = true;
          // NetHelper().addAIO(deviceInfoEntity).then((value) {
          //   NavigatorUtil.replace(context, MyDevicePage(isNeedSetWifi: true, isShowSetWifiTips: true));
          // });
        }else if(decodeEntity.validateResult==2){
          connTimer?.cancel();
          // DeviceConfigEntity.getInstance().isBind = true;
          // NetHelper().addAIO(deviceInfoEntity).then((value) {
          //   NavigatorUtil.replace(context, MyDevicePage(isNeedSetWifi: true, isConnectedWifi: true));
          // });
        }else if(decodeEntity.validateResult==0){
          connTimer?.cancel();
          // disconnectDevice(deviceName);
          ToastUtils.showToast(msg: "用户取消绑定，无法连接");
        }else{
          connTimer?.cancel();
          // disconnectDevice(deviceName);
          ToastUtils.showToast(msg: "该设备已被其他设备绑定，无法连接");
        }
      } else if (decodeEntity.name == 'aioInfo') {
        ///查询一体机信息成功
        LogUtils.log('查询一体机信息成功');
        setState(() {
          aioInfo = decodeEntity.info;
        });
        ///查询额贴设备信息
        List<int> cmdList = [0xbb, 0x06, 0x00, 0x00, 0x00];
        NativeUtils.nativeAIOListener(cmdList);
      } else if (decodeEntity.name == 'pasterInfo') {
        ///查询额贴信息成功
        LogUtils.log('查询脑贴信息成功');
        setState(() {
          pasterInfo = decodeEntity.info;
        });
      } else if (decodeEntity.name == 'setWifi') {
        LogUtils.log('setWifi');
        DecodeEntity decodeEntity = AIODecode.decodeData(cmdList);
        if (decodeEntity.name == 'setWifi') {
          ///设置 wifi 成功
          if (decodeEntity.result) {
            LogUtils.log('设置wifi成功');
            Loading.getIns().hide();
            ToastUtils.showToast(msg: '连接wifi成功');
            setState(() {
              aioInfo['wifi_open'] = true;
              aioInfo['wifi_connected'] = true;
              aioInfo['status'] = 'Y';
            });
          } else {
            LogUtils.log('wifi密码不正确');
            setState(() {
              aioInfo['status'] = 'N';
              aioInfo['wifi_connected'] = false;
            });
            Loading.getIns().hide();
            ToastUtils.showToast(msg: '配网失败');
          }
        }
      }
    }
  }


}
